package com.hy.controller;

import com.hy.base.MinIOConfig;
import com.hy.base.MinIOUtils;
import com.hy.grace.result.GraceJSONResult;
import com.hy.grace.result.ResponseStatusEnum;
import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private MinIOConfig minIOConfig;

    /**
     * 上传面试官图片
     * @return
     */
    @PostMapping("/uploadInterviewerImage")
    private GraceJSONResult uploadInterviewerImage(@RequestParam("file") MultipartFile file) throws Exception {
        // 获取文件原始名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        fileName = "interviewer/" + dealWithoutFileName(fileName);
        String imageUrl = MinIOUtils.uploadFile(
                minIOConfig.getBucketName(),
                fileName,
                file.getInputStream(),
                true);

        return GraceJSONResult.ok(imageUrl);
    }

    /**
     * 上传面试官口播视频
     * @return
     */
    @PostMapping("/uploadInterviewVideo")
    private GraceJSONResult uploadInterviewVideo(@RequestParam("file") MultipartFile file) throws Exception {
        // 获取文件原始名称
        String fileName = file.getOriginalFilename();
        if (StringUtils.isBlank(fileName)){
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        fileName = "interviewVideo/" + dealWithoutFileName(fileName);
        String videoUrl = MinIOUtils.uploadFile(
                minIOConfig.getBucketName(),
                fileName,
                file.getInputStream(),
                true);

        return GraceJSONResult.ok(videoUrl);
    }

    private String dealWithFileName(String originalFilename) {
        // 获取文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 获取无后缀的文件名
        String fileName = originalFilename.substring(0, originalFilename.lastIndexOf("."));
        // 生成uuid
        String uuid = UUID.randomUUID().toString();

        return fileName + "-" + uuid + suffixName;

    }

    private String dealWithoutFileName(String originalFilename) {
        // 获取文件后缀名
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 生成uuid
        String uuid = UUID.randomUUID().toString();

        return uuid + suffixName;
    }
}
